import 'package:flutter/material.dart';

class OverlayPageView extends StatefulWidget {
  final List<Widget> pages;

  const OverlayPageView({super.key, required this.pages});

  @override
  State<OverlayPageView> createState() => _OverlayPageViewState();
}

class _OverlayPageViewState extends State<OverlayPageView> {
  final PageController pageController = PageController();
  double pageOffset = 0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    pageController.addListener(() {
      // 可以在这里添加更多自定义逻辑，例如打印当前页面位置
      pageOffset = pageController.page??0;
    });
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    pageController.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return PageView.builder(
      controller: pageController,
      itemCount: widget.pages.length,
      itemBuilder: (BuildContext context, int index) {
        return PageTransformer(
          page: widget.pages[index],
          position: index,
          pageOffset: pageOffset,
        );
      },
    );
  }
}

class PageTransformer extends StatelessWidget {
  final Widget page;
  final int position;
  final double pageOffset;

  const PageTransformer(
      {super.key,
      required this.page,
      required this.position,
      required this.pageOffset});

  @override
  Widget build(BuildContext context) {
    final pageViewHeight = MediaQuery.of(context).size.height;
    final pageViewWidth = MediaQuery.of(context).size.width;
    // final value = position - PageView.of(context).page!;
    double pageOffset = 0;
    /* if (pageController.hasClients) {
      pageOffset = pageController.page ?? 0.0;
    } */
    double value = position - pageOffset;
    final opacity = (1 - (value.abs() * 1.5)).clamp(0.0, 1.0);
    final scale = (1 - (value.abs() * 0.5)).clamp(0.0, 1.0);
    final yOffset = value * pageViewHeight;

    return Opacity(
      opacity: opacity,
      child: Transform(
        transform: Matrix4.identity()
          ..translate(0, yOffset)
          ..scale(scale),
        child: page,
      ),
    );
  }
}
